'''
Created on 21/dic/2010

@author: rbutti
'''
import os
from google.appengine.ext.webapp import template

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users

from google.appengine.ext import db

from django.utils import simplejson

from models import schema
from business import boplaylist


class ApiSongHandler(webapp.RequestHandler):
    
    def getPlaylistFromRequest(self):
        '''
        restituisce il valore della playlist nella request
        '''
        playlist = self.request.get('playlist')
        if not playlist:
            playlist="Principale"
        if playlist=="":
            playlist="Principale"
        return playlist

    def list(self):
        print "A"
    
    def add(self):
        #print "B"
        #recupero il nome della playlist
        playlist = self.getPlaylistFromRequest()
        #recupero l'identificatore del video
        videoId = self.request.get('videoid')
        #recupero  l'utente
        user = users.get_current_user()
        if user:
            userId=user.user_id()
            bp = boplaylist.BoPlaylist()
            result = {}
            if bp.addSongForUser(playlist, videoId, user):
                
                result["status"] = "OK"
                result["videoid"] = videoId
                result["userid"] = userId
            else:
                result={}
                result["status"] = "KO"
                result["message"] = "video id not valid"
            self.response.headers['Content-Type'] = "application/json"
            self.response.out.write(simplejson.dumps(result, sort_keys=True, indent=4))
        else:
            self.error(403)
        #print playlist
        
    
    def get (self,action):
        #print action
        if action == 'list':
            self.list()
        elif action == 'add':
            self.add()
            
class ApiPlaylistHandler(webapp.RequestHandler):
    def list(self):
        user = users.get_current_user()
        if user:
            listPlaylist = boplaylist.BoPlaylist().loadUserPlaylist(user)
            template_values = {
                "is_auth": True,
                'user': user,
                'playlist': listPlaylist,
            }
            path = os.path.join(os.path.dirname(__file__), '../templates/blocks/playlist.phtml')
            self.response.out.write(template.render(path, template_values))

        else:
            self.error(403)
        
    def add(self):
        print "add"
        
    def get (self,action):
        #print action
        if action == 'list':
            self.list()
        elif action == 'add':
            self.add()
    
def main():
    application = webapp.WSGIApplication([
        ('/api/song/(list|add)', ApiSongHandler),
        ('/api/playlist/(list|add|edit)', ApiPlaylistHandler),
        ],debug=True)
    run_wsgi_app(application)

if __name__ == "__main__":
  main()
